package com.distributed.netty.client;

import com.distributed.netty.encode.MessageDecoder;
import com.distributed.netty.encode.MessageEncoder;
import com.distributed.netty.entity.ElementJob;
import com.distributed.netty.entity.Message;
import com.distributed.netty.server.HeartBeatServerHandler;
import com.distributed.netty.server.HeartBeatServerInitializer;
import com.rcache.core.cache.Rcache;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.Timer;
import org.apache.log4j.Logger;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * @desc	初始化管道操作	
 * @author	高增源
 * @time	2021年11月18日
 */
public class HeartBeatClientInitializer extends ChannelInitializer<SocketChannel>{
	Rcache cache;
	LinkedList<ElementJob> jobList;
	ConnectionWatchdog connectionWatchdog;
	Logger LOG=Logger.getLogger(HeartBeatServerInitializer.class);
	public HeartBeatClientInitializer(Bootstrap bootstrap, Timer timer, boolean reconnect, Rcache cache, LinkedList<ElementJob> jobList){
		connectionWatchdog = new ConnectionWatchdog(bootstrap, timer, reconnect,cache,jobList);
		this.cache=cache;
		this.jobList=jobList;
	}
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		LOG.debug("slave初始化通道……");
		ChannelPipeline pipe = ch.pipeline();
//		pipe.addLast(new MessageDecoder());
//		pipe.addLast(new MessageEncoder());
		//设置心跳每4秒读一次
		pipe.addLast("idle",new IdleStateHandler(0,4,0,TimeUnit.SECONDS));
		pipe.addLast(new ObjectEncoder());
		pipe.addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(Message.class.getClassLoader())));

		pipe.addLast("ChatHandler",new ChatHandler(cache,jobList));
//		pipe.addLast("HeartBeatClientHandler",new HeartBeatClientHandler(jobList));
		pipe.addLast(connectionWatchdog);
	}

}
